package cn.lyq.card.ui.qualified

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lyq.card.R
import cn.lyq.card.base.BaseFg
import cn.lyq.card.data.src.Status
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.fg_refresh_rv.*


class CashBackStageFg : BaseFg() {

    private val mModel by lazy {
        getVMActivity(CashBackVM::class.java)
    }
    private val mIndex by lazy {
        arguments?.getInt(KEY_INDEX, 0) ?: 0
    }
    private val mAdapter by lazy {
        CashBackStageAdapter(requireContext(), mutableListOf())
    }

    companion object {
        private const val KEY_INDEX = "INDEX"

        fun newInstance(index: Int): CashBackStageFg {
            val args = Bundle()
            args.putInt(KEY_INDEX, index)
            val fragment = CashBackStageFg()
            fragment.arguments = args
            return fragment
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fg_refresh_rv
    }

    override fun initView(view: View) {
        super.initView(view)
        rv.layoutManager = LinearLayoutManager(requireContext())
        rv.adapter = mAdapter

        mAdapter.onClick = object : CashBackStageAdapter.OnClick {
            override fun click(position: Int, levelIndex: Int) {
                val data = mAdapter.data[position]
                if (data.list?.size != 0) {
                    QualifiedStoreActivity.start(requireContext(), data, levelIndex)
                }
            }
        }
    }

    override fun initListener(view: View) {
        super.initListener(view)
        refreshLayout.setOnRefreshListener {
            getData()
        }
    }

    override fun initObserver() {
        super.initObserver()
        mModel.goodsId.observe(this, Observer {
            getData()
        })
    }

    private fun getData() {
        mModel.getCashBackStageList(mIndex).observe(this, Observer { result ->
            when (result?.status) {
                Status.LOADING -> refreshLayout.isRefreshing = true
                Status.SUCCESS -> {
                    refreshLayout.isRefreshing = false
                    mAdapter.data.clear()
                    val elements = result.requireData()
                    elements.forEach {
                        it.list?.sort()
                    }
                    mAdapter.data.addAll(elements)
                    mAdapter.notifyDataSetChanged()
                }
                Status.ERROR -> {
                    ToastUtils.showShort(result.message.getMsg())
                    refreshLayout.isRefreshing = false
                }
            }
        })
    }
}